package com.omg.server.framework.service;

import java.util.concurrent.BlockingQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.omg.server.common.Constants;
import com.omg.server.crawler.RequestConsumerThread;
import com.omg.server.crawler.RequestContext;
import com.omg.server.util.CommonUtil;
import com.omg.server.util.PropertiesHelper;

/**
 * 启动抓取数据请求(消费者)线程池服务
 *
 */
public class ProcessThreadInitService {
	private static final Log log = LogFactory.getLog(ProcessThreadInitService.class); 
	private static final int DEFAULTTHREADSIZE = 10;
	private ThreadGroup requestThreadGroup;
	
	public ProcessThreadInitService(BlockingQueue<RequestContext> requestQueue){
		initThreadPool(requestQueue);
	}
	
	public void initThreadPool(BlockingQueue<RequestContext> requestQueue){
		String rcThreadSizeCfg = PropertiesHelper.getProperty(Constants.REQUSTQUEUETHEADSIZE);
		
		log.info("初始化线程池开始....");
		int threadSize = DEFAULTTHREADSIZE;
		if (CommonUtil.isNumber(rcThreadSizeCfg)){
			threadSize = Integer.valueOf(rcThreadSizeCfg);
		}
		
		Thread[] thread = new RequestConsumerThread[threadSize];
		requestThreadGroup = new ThreadGroup("请求处理线程组"); //方便管理线程组
		for (int i=0; i < threadSize; i++){
			thread[i] = new RequestConsumerThread(requestQueue);
			thread[i].setName("请求处理线程" + (i+1));
			thread[i].start();
		}
		requestThreadGroup.enumerate(thread);
		
		log.info("初始化请求处理线程池成功, size:" + threadSize);
	}

	public ThreadGroup getRequestThreadGroup() {
		return requestThreadGroup;
	}

}
